package com.my.content.search;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.my.content.liveproject.R;

public class SearchActivity extends AppCompatActivity {

    private EditText et;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_search);
        et = (EditText) findViewById(R.id.search_et);//搜索框控件
        //搜索框的触摸监听，当触摸时，hint的提示文本内容置为空
        et.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                et.setHint("");
                return false;
            }
        });
        /* 搜索框的另一个key监听，作用是输入完内容时，点击软键盘的回车功能时，
        *  隐藏软键盘，并得到搜索框内的搜索关键词
        */
        et.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
                if (keyCode == keyEvent.KEYCODE_ENTER) {
                    //得到搜索文本
                    String searchText = et.getText().toString().trim();
                    //隐藏软键盘
                    InputMethodManager imm = (InputMethodManager) getSystemService(SearchActivity.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                    //让et失去焦点
                    et.clearFocus();
                    Toast.makeText(SearchActivity.this, "您搜索了：" + searchText, Toast.LENGTH_SHORT).show();
                }
                return false;
            }
        });
    }

    //取消按钮，功能是关闭搜索这个页面
    public void cancel(View view) {
        finish();
    }
}
